const { access, appendFile } = require('fs/promises')
const { constants, readFileSync, readdirSync, mkdirSync } = require('fs')
const fs = require('fs')
const path = require('path')
const { resolve, targetFolder, removeDir } = require('./utils')
const template = readFileSync(path.resolve(__dirname, './index.html'), 'utf8')
let fileIndex = 0

async function main(fileOrFolders) {
  await createFolder()
  await mergeFiles(fileOrFolders)
}
async function mergeFiles(fileOrFolders) {
  for (const item of fileOrFolders) {
    try {
      const p = resolve(item)
      await access(p, constants.F_OK)
      await appendData(p)
    } catch(e) {
      console.log(e)
    }
  }
}

async function createFolder() {
  try {
    await access(targetFolder, constants.F_OK)
    await removeDir(targetFolder)
  } catch(e) {
  }
  await mkdirSync(targetFolder)
}

async function appendData(f) {
  const stats = fs.statSync(f)
  if (stats.isFile()) {
    fileIndex += 1
    let content = readFileSync(f, 'utf8')
    content = content.replace(/\$/g, /\\$/)
    const new_content = template.replace('<!-- inject data -->', content)
    await appendFile(`${targetFolder}/${fileIndex}.html`, new_content, 'utf8')
  } else {
    const arr = readdirSync(f)
    for (const item of arr) {
      await appendData(`${f}/${item}`)
    }
  }
}

module.exports = main